package com.dong.mcd.service.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dong.mcd.dao.CommMapping;
import com.dong.mcd.service.ICommService;
import com.dong.mcd.util.CollectionUtil;

@Transactional
@Service("commService")
public class CommServiceImpl implements ICommService {

	@Autowired
	private CommMapping mapping;
	@Autowired
	private DataSource dataSource;

	public List<Map<String, Object>> queryBySql(String sql) {
		return mapping.queryBySql(sql);
	}

	public List<String> queryColumnBySql(String sql) {
		List<Map<String, Object>> columnMap = mapping.queryColumnBySql(sql);
		List<String> columns = new ArrayList<String>();
		if (!CollectionUtil.isEmpty(columnMap)) {
			Iterator<String> itr = columnMap.get(0).keySet().iterator();
			while (itr.hasNext()) {
				String key = itr.next();
				columns.add(key);
			}
		}
		return columns;
	}

	public Map<String, Object> executeSql(String sql) throws SQLException {
		Connection conn = dataSource.getConnection();
		Statement stmt = conn.createStatement();
		Map<String, Object> result = new HashMap<String, Object>();
		ResultSet rt = stmt.executeQuery(sql);
		ResultSetMetaData metaData = rt.getMetaData();
		List<String> columns = new ArrayList<String>();
		for (int i = 0; i < metaData.getColumnCount(); i++) {
			String columnName = metaData.getColumnName(i + 1);
			columns.add(columnName);
		}
		result.put("columns", columns);
		List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
		while (rt.next()) {
			Map<String, Object> map = new HashMap<String, Object>();
			for (int i = 0; i < columns.size(); i++) {
				String key = columns.get(i);
				map.put(key, rt.getObject(key));
			}
			datas.add(map);
		}
		result.put("datas", datas);
		rt.close();
		stmt.close();
		return result;
	}

}
